package com.nuc.thread.cas.automicrefrence;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicReference;

/**
 * @author 诗酒趁年华
 * @version 1.0.0
 * @Description 原子引用 ABA问题
 * @createTime 2021年07月12日 12:44:00
 */
@Slf4j
public class Test {
    private static AtomicReference<String> reference = new AtomicReference<>("A");
    public static void main(String[] args) throws InterruptedException {
        String prev = reference.get();
        other();//主线程并不知道其他线程曾经修改过共享变量的值
        Thread.sleep(1000);//休眠一秒

        log.debug("主线程修改的结果为：{}",reference.compareAndSet(prev,"C"));
        log.debug("当前共享变量中的值为:{}",reference.get());
    }

    static void other() throws InterruptedException {
        new Thread(()->{
            log.debug("修改结果 A->B");
            String prev = reference.get();
            reference.compareAndSet(prev,"B");
        },"t1").start();

        Thread.sleep(500);
        new Thread(()->{
            log.debug("修改结果 B->A");
            String prev = reference.get();
            reference.compareAndSet(prev,"A");
        },"t2").start();

    }

}
